package com.youi.web;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.youi.exception.BusinessException;
import com.youi.manage.HttpRequestManage;
import com.youi.manage.HttpSessionManage;
import com.youi.common.DelStatus;
import com.youi.common.SessionKey;
import com.youi.service.GoodsService;
import com.youi.service.GoodsandgoodscarService;
import com.youi.service.GoodscarService;
import com.youi.service.GoodssizeService;
import com.youi.entity.Goods;
import com.youi.entity.Goodsandgoodscar;
import com.youi.entity.Goodscar;
import com.youi.entity.Goodssize;
import com.youi.entity.User;
import com.youi.common.Common;
import com.youi.util.CommonInfoUtil;
import com.youi.util.DateUtil;
import com.youi.util.JedisUtils;
import com.youi.util.JsonUtil;
import com.youi.util.ObjectUtil;
import com.youi.util.Page;

/**
* Goodsandgoodscar控制层
* @author Administrator
*/
@Controller
public class GoodsandgoodscarController  extends HttpRequestManage implements ApplicationContextAware{

		@Autowired
		private GoodsandgoodscarService goodsandgoodscarService;
		@Autowired
		private GoodscarService goodscarService;
		@Autowired
		private GoodsService goodsService;
		@Autowired
		private GoodssizeService goodssizeService;

		/**同步静态对象 零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码：生成零长度的byte[]对象只需3条操作码，而Object lock = new Object()则需要7行操作码*/
		private static byte[] lock =null;
		/**
		 * 
		 * 新增或编辑购物车的商品
		*/
		@ResponseBody
		@RequestMapping("addOrEditGoodsandgoodscar")
		public String addOrEditGoodsandgoodscar(ModelMap modelMap,HttpServletRequest request)throws BusinessException,ParseException{
			Long id=optLong("id",request);
			Goodsandgoodscar goodsandgoodscar=null;
			if (id!=null) {
				goodsandgoodscar=goodsandgoodscarService.get(id);
			}else {
				goodsandgoodscar=new Goodsandgoodscar();
				goodsandgoodscar.setDelStatus(DelStatus.NODEL);
				goodsandgoodscar.setGmtCreated(new Date());
			}
			Long goodscarId=optLong("goodscarId",request);
			if (goodscarId!=null){
				goodsandgoodscar.setGoodscarId(goodscarId);
			}
			Long goodsId=optLong("goodsId",request);
			if (goodsId!=null){
				goodsandgoodscar.setGoodsId(goodsId);
			}
			String specification=optString("specification",request);
			if (specification!=null){
				goodsandgoodscar.setSpecification(specification);
			}
			Integer count=optInteger("count",request);
			if (count!=null){
				goodsandgoodscar.setCount(count);
			}
			goodsandgoodscar.setGmtModify(new Date());
			goodsandgoodscarService.saveOrUpdate(goodsandgoodscar);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}

		/**
		 * M-12
		 * 删除购物车的商品
		*/
		@ResponseBody
		@RequestMapping("userGetInfo/delGoodsandgoodscarByIds")
		public String delGoodsandgoodscarByIds(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
			String ids=getString("ids",request);
			Map<String, Object> params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.USERID, user.getId());
			Goodscar goodscar=goodscarService.getByParam(params);
			if (goodscar==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "购物车不存在");
			}			
			List<Long> idsList=ObjectUtil.getIdListByIds(ids);
			if (idsList==null||idsList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.PARAMERROR, "ids参数错误");
			}
			params=new HashMap<String, Object>();
			params.put(Common.DELSTATUS, DelStatus.NODEL);
			params.put(Common.ID, idsList);
			List<Goodsandgoodscar> goodsandgoodscarList= goodsandgoodscarService.getByParams(params);
			if (goodsandgoodscarList==null||goodsandgoodscarList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			Double amount=0.00;
			for (Goodsandgoodscar goodsandgoodscar : goodsandgoodscarList) {
				goodsandgoodscar.setDelStatus(DelStatus.DEL);	
				amount+=goodsandgoodscar.getAmount();
			}
			goodsandgoodscarService.saveOrUpdateAll(goodsandgoodscarList);		
			goodscar.setAmount(goodscar.getAmount()-amount);
			goodscarService.saveOrUpdate(goodscar);
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");
		}

		/**
		 * 分页查询Goodsandgoodscar
		*/
		@ResponseBody
		@RequestMapping("getGoodsandgoodscar")
		public String getGoodsandgoodscar(ModelMap modelMap,HttpServletRequest request) throws BusinessException,ParseException{
			Integer pageIndex=optInteger("pageIndex",request,1);
			Integer pageNum=optInteger("pageNum",request,10);
			String des=optString("des",request,Common.DESC);
			String pms=optString("pms",request);
			Date start=optDate("start",request,"yyyy-MM-dd HH:mm:ss");
			Date end=optDate("end",request,"yyyy-MM-dd HH:mm:ss");
			Map<String, Object> prams=new HashMap<String, Object>();
			prams.put(Common.DELSTATUS, DelStatus.NODEL);
			Map<String, Object> sortPram=new HashMap<String, Object>();
			sortPram.put(Common.ID,des);
			Map<String, Object> searchPram=null;
			if (pms!=null) {
				searchPram=new HashMap<String, Object>();
			}
			Map<String, Object> startTime=null;
			if(start!=null){
				startTime=new HashMap<String, Object>();
				startTime.put(Common.GMTCREATED,start);
			}
			Map<String, Object> endTime=null;
			if(end!=null){
				endTime=new HashMap<String, Object>();
				endTime.put(Common.GMTCREATED,end);
			}
			List<Goodsandgoodscar> goodsandgoodscarList=goodsandgoodscarService.getByParamsList(prams, searchPram,sortPram,  (pageIndex-1)*pageNum, pageNum, startTime, endTime);
			if (goodsandgoodscarList==null||goodsandgoodscarList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			Integer pageCount=goodsandgoodscarService.getCountByParamss(prams, searchPram, startTime, endTime);
			modelMap.put(CommonInfoUtil.PAGECOUNT, Page.getCount(pageCount, pageNum));//pageCount  总页数
			modelMap.put(CommonInfoUtil.PAGEINDEX, pageIndex);			//pageIndex     查询页数
			modelMap.put(CommonInfoUtil.ALLCOUINT,pageCount);
			modelMap.put(CommonInfoUtil.DATA, goodsandgoodscarList);		//jsonObjectList json对象集合
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",modelMap);
		}

		/**
		 * M-13
		 * 编辑购物车的商品数量
		*/
		@ResponseBody
		@RequestMapping("userGetInfo/editGoodsandgoodscarCount")
		public String editGoodsandgoodscarCount(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			synchronized (lock) {
				User user=(User) HttpSessionManage.getAttribute(request, SessionKey.USER);
				Map<String, Object> params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put(Common.USERID, user.getId());
				Goodscar goodscar=goodscarService.getByParam(params);
				if (goodscar==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "购物车不存在");
				}			
				Long id=getLong("id",request);
				Integer count=getInteger("count",request);
				Goodsandgoodscar goodsandgoodscar=goodsandgoodscarService.get(id);
				if (goodsandgoodscar==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
				}
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put(Common.ID, goodsandgoodscar.getGoodssizeId());
				Goodssize goodssize=goodssizeService.getByParam(params);
				if (goodssize==null) {
					return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
				}
				if (count>goodssize.getRealStockNum()) {
					return JsonUtil.toJson(CommonInfoUtil.ISLOCK, "商品库存不足");
				}
				params=new HashMap<String, Object>();
				params.put(Common.DELSTATUS, DelStatus.NODEL);
				params.put(Common.ID, goodssize.getGoodsId());
				Goods goods=goodsService.getByParam(params);
				if (goods==null||goods.getStatus()!=1) {
					return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "商品不存在或非出售状态无法添加到购物车");
				}
				if (goodsandgoodscar.getCount()>goodssize.getRealStockNum()) {
					return JsonUtil.toJson(CommonInfoUtil.NOPERMISSIONS, "购物车该商品数量大于当前库存");
				}
				goodsandgoodscar.setCount(count);
				goodsandgoodscar.setAmount(goodssize.getPrice()*count);
				if (goodsandgoodscar.getCount()==0) {
					goodscar.setAmount(goodscar.getAmount()-goodsandgoodscar.getAmount());
					goodscarService.saveOrUpdate(goodscar);
					goodsandgoodscar.setDelStatus(DelStatus.DEL);				
				}
				goodsandgoodscarService.saveOrUpdate(goodsandgoodscar);			
				return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成");//jsonObject	json对象
			}
		}
		
		/**
		 *根据id查询Goodsandgoodscar
		*/
		@ResponseBody
		@RequestMapping("getGoodsandgoodscarById")
		public String getGoodsandgoodscarById(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			Long id=getLong("id",request);
			Goodsandgoodscar goodsandgoodscar=goodsandgoodscarService.get(id);
			if (goodsandgoodscar==null) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",goodsandgoodscar);//jsonObject	json对象
		}

		/**
		 * 查询所有Goodsandgoodscar
		 * @param modelMap
		 * @param session
		 * @return
		 */
		@ResponseBody
		@RequestMapping("getAllGoodsandgoodscar")
		public String getAllGoodsandgoodscar(ModelMap modelMap,HttpServletRequest request) throws BusinessException{
			List<Goodsandgoodscar> goodsandgoodscarList= goodsandgoodscarService.getByParams(null);
			if (goodsandgoodscarList==null||goodsandgoodscarList.size()==0) {
				return JsonUtil.toJson(CommonInfoUtil.NULLDATA, "空数据");
			}
			return JsonUtil.toJson(CommonInfoUtil.SUCCESS, "操作完成",goodsandgoodscarList);//jsonObjectList	json对象集合
		}

		/**定时器线程池*/
		private static ScheduledThreadPoolExecutor executor;
		@Override
		public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
			// TODO Auto-generated method stub
			if (lock==null) {
				lock = new byte[0];
				executor=new ScheduledThreadPoolExecutor(1);				
			}
		}
}
